<template>
  <div class="dialog-form">
    <el-form ref="machineryRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="车载厂商" prop="firmName">
        <el-select clearable v-model="form.firmName" placeholder="请选择车载厂商">
          <el-option
            v-for="item in terminal_company"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="车载机具编号" prop="num">
        <el-input v-model="form.num" placeholder="请输入车载机具编号" />
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onConfirm">确认</el-button>
    </div>
  </div>
</template>

<script setup>
import { getMachinery, addMachinery, updateMachinery } from "@/api/bus/machinery"

const { proxy } = getCurrentInstance()
const { terminal_company } = proxy.useDict('terminal_company')

const machineryRef = ref()
const emits = defineEmits(['cancel', 'confirm'])

const form = ref({
  id: null,
  num: null,
  firmName: ''
})
const rules = {
  num: [
    { required: true, message: "车载机具编号不能为空", trigger: "blur" }
  ],
  firmName: [
    { required: true, message: "请选择车载厂商", trigger: "blur" }
  ]
}

const pageInit = (id) => {
  if (id) {
    getMachinery(id).then(response => {
      form.value = response.data
    })
  }
}

const onCancel = () => {
  emits('cancel')
}

const onConfirm = () => {
  machineryRef.value.validate(valid => {
    if (valid) {
      if (form.value.id) {
        updateMachinery(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          machineryRef.value.resetFields()
          emits('confirm')
        })
      } else {
        addMachinery(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          machineryRef.value.resetFields()
          emits('confirm')
        })
      }
    }
  })
}

defineExpose({
  pageInit
})

</script>

<style lang="scss" scoped>

</style>